package com.xxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxx.server.config.JwtTokenUtil;
import com.xxx.server.mapper.AdminMapper;
import com.xxx.server.pojo.Admin;
import com.xxx.server.pojo.RespBean;
import com.xxx.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author psycho
 * @since 2021-11-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;
    //spring security 加密工具类
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private AdminMapper adminMapper;



    /**
     * 登录之后返回token
     */
    @Override
    public RespBean login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //如果用户详情不存在，或前端传入密码与数据库中加密密码不匹配(passwordEncoder.matches--->spring security密码加密匹配）
        if(userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())){
            return RespBean.error("用户名或密码错误!");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("账号被禁用，清联系管理员。");
        }

        /**
         * 更新security登录用户对象
         * UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
         * 参数1：用户详情  参数2：密码  参数3：权限列表
         */
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //将令牌authenticationToken放到security全局中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //根据用户详情获取token
        String token = jwtTokenUtil.generateToken(userDetails);

        Map<String , String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        //添加头部信息
        tokenMap.put("tokenHead", tokenHead);

        //登录成功之后将tokenMap返回给前端
        return RespBean.success("登录成功",tokenMap);
    }

    /**
     * 根据用户名获取用户对象
     */
    @Override
    public Admin getAdminByUserName(String userName) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", userName).eq("enabled", true));
    }
}
